package com.gsy.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.collect.Maps;
import com.gsy.exception.TokenErrorException;
import com.gsy.request.BaseRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * token工具类
 */
public class JwtUtils {
    /**
     * 过期时间为30分钟
     *
     */
    private static final long EXPIRE_TIME = 30*60*1000;

    /**
     * token私钥
     */
    private static final String TOKEN_SECRET = "hjs993jkcnxaO5FDS66532KIFW899jfkj";

    /**
     * 生成签名
     * @param userId
     * @return
     */
    public static String sinToken(Integer userId, String userName, Integer type){
        //过期时间
//        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(3);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //附带userID生成签名
        return JWT.create().withHeader(header).withClaim("userId",userId).withClaim("userName", userName)
                .withClaim("type", type).sign(algorithm);
    }

    /**
     * 解析签名
     * @param token
     * @return
     */
    public static Map<String, Object> verity(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);

            Map<String, Claim> claims = jwt.getClaims();
            Claim claim = claims.get("userId");
            Long userId = claim.asLong();
            Claim claimName = claims.get("userName");
            String userName = claimName.asString();
            Claim type = claims.get("type");
            Integer typeString = type.asInt();

            Map<String, Object> map = Maps.newHashMap();
            map.put("userId", userId);
            map.put("userName", userName);
            map.put("type", typeString);

            return map;
        } catch (IllegalArgumentException | JWTVerificationException e) {
            throw new TokenErrorException("令牌token非法！");
        }

    }

    /**
     * 解析用户名
     * @param request
     * @return
     */
    public static String getUsername(BaseRequest request){
//        return verity(request.getToken()).get("userName").toString();
        return "dangqian";
    }

}
